const UserService = require('./userService');
const JournalPaperService = require('./journalPaperService');

/**
 * 数据库服务管理器
 * 提供统一的数据库操作接口
 */
class DatabaseService {
  constructor() {
    this.userService = new UserService();
    this.journalPaperService = new JournalPaperService();
  }

  /**
   * 获取用户服务实例
   * @returns {UserService} 用户服务实例
   */
  getUserService() {
    return this.userService;
  }

  /**
   * 获取期刊论文服务实例
   * @returns {JournalPaperService} 期刊论文服务实例
   */
  getJournalPaperService() {
    return this.journalPaperService;
  }

  /**
   * 用户相关操作
   */
  get users() {
    return {
      // 创建用户
      create: (userData) => this.userService.createUser(userData),
      
      // 根据ID获取用户
      getById: (userId) => this.userService.getUserById(userId),
      
      // 根据用户名获取用户
      getByUsername: (username) => this.userService.findUserByUsername(username),
      
      // 获取所有用户
      getAll: (filters) => this.userService.getAllUsers(filters),
      
      // 更新用户
      update: (userId, updateData) => this.userService.updateUser(userId, updateData),
      
      // 删除用户
      delete: (userId) => this.userService.deleteUser(userId),
      
      // 验证登录
      validateLogin: (username, password) => this.userService.validateLogin(username, password),
      
      // 更新密码
      updatePassword: (userId, newPassword) => this.userService.updatePassword(userId, newPassword),
      
      // 更新用户状态
      updateStatus: (userId, status) => this.userService.updateUserStatus(userId, status),
      
      // 搜索用户
      search: (keyword) => this.userService.searchUsers(keyword)
    };
  }

  /**
   * 期刊论文相关操作
   */
  get papers() {
    return {
      // 创建论文
      create: (paperData) => this.journalPaperService.createPaper(paperData),
      
      // 根据ID获取论文
      getById: (paperId) => this.journalPaperService.getPaperById(paperId),
      
      // 获取所有论文
      getAll: (filters) => this.journalPaperService.getAllPapers(filters),
      
      // 更新论文
      update: (paperId, updateData) => this.journalPaperService.updatePaper(paperId, updateData),
      
      // 删除论文
      delete: (paperId) => this.journalPaperService.deletePaper(paperId),
      
      // 根据作者搜索论文
      getByAuthor: (author) => this.journalPaperService.getPapersByAuthor(author),
      
      // 根据期刊搜索论文
      getByJournal: (journalName) => this.journalPaperService.getPapersByJournal(journalName),
      
      // 根据专业领域搜索论文
      getByField: (field) => this.journalPaperService.getPapersByField(field),
      
      // 综合搜索论文
      search: (keyword) => this.journalPaperService.searchPapers(keyword),
      
      // 获取论文统计信息
      getStatistics: () => this.journalPaperService.getPaperStatistics(),
      
      // 根据年份范围获取论文
      getByYearRange: (startYear, endYear) => this.journalPaperService.getPapersByYearRange(startYear, endYear)
    };
  }

  /**
   * 获取系统统计信息
   * @returns {Promise<Object>} 系统统计信息
   */
  async getSystemStatistics() {
    try {
      const [userStats, paperStats] = await Promise.all([
        this.getUserStatistics(),
        this.papers.getStatistics()
      ]);

      return {
        users: userStats,
        papers: paperStats,
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      console.error('获取系统统计信息失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户统计信息
   * @returns {Promise<Object>} 用户统计信息
   */
  async getUserStatistics() {
    try {
      const allUsers = await this.users.getAll();
      const activeUsers = allUsers.filter(user => user.status === 1);
      const inactiveUsers = allUsers.filter(user => user.status === 0);

      return {
        total_users: allUsers.length,
        active_users: activeUsers.length,
        inactive_users: inactiveUsers.length
      };
    } catch (error) {
      console.error('获取用户统计信息失败:', error);
      throw error;
    }
  }

  /**
   * 批量操作接口
   */
  get batch() {
    return {
      /**
       * 批量创建用户
       * @param {Array} usersData - 用户数据数组
       * @returns {Promise<Array>} 创建结果
       */
      createUsers: async (usersData) => {
        const results = [];
        for (const userData of usersData) {
          try {
            const userId = await this.users.create(userData);
            results.push({ success: true, id: userId, data: userData });
          } catch (error) {
            results.push({ success: false, error: error.message, data: userData });
          }
        }
        return results;
      },

      /**
       * 批量创建论文
       * @param {Array} papersData - 论文数据数组
       * @returns {Promise<Array>} 创建结果
       */
      createPapers: async (papersData) => {
        const results = [];
        for (const paperData of papersData) {
          try {
            const paperId = await this.papers.create(paperData);
            results.push({ success: true, id: paperId, data: paperData });
          } catch (error) {
            results.push({ success: false, error: error.message, data: paperData });
          }
        }
        return results;
      },

      /**
       * 批量删除用户
       * @param {Array} userIds - 用户ID数组
       * @returns {Promise<Array>} 删除结果
       */
      deleteUsers: async (userIds) => {
        const results = [];
        for (const userId of userIds) {
          try {
            const changes = await this.users.delete(userId);
            results.push({ success: true, id: userId, changes });
          } catch (error) {
            results.push({ success: false, error: error.message, id: userId });
          }
        }
        return results;
      },

      /**
       * 批量删除论文
       * @param {Array} paperIds - 论文ID数组
       * @returns {Promise<Array>} 删除结果
       */
      deletePapers: async (paperIds) => {
        const results = [];
        for (const paperId of paperIds) {
          try {
            const changes = await this.papers.delete(paperId);
            results.push({ success: true, id: paperId, changes });
          } catch (error) {
            results.push({ success: false, error: error.message, id: paperId });
          }
        }
        return results;
      }
    };
  }

  /**
   * 数据导出功能
   */
  get export() {
    return {
      /**
       * 导出所有用户数据
       * @returns {Promise<Array>} 用户数据
       */
      users: async () => {
        return await this.users.getAll();
      },

      /**
       * 导出所有论文数据
       * @returns {Promise<Array>} 论文数据
       */
      papers: async () => {
        return await this.papers.getAll();
      },

      /**
       * 导出系统完整数据
       * @returns {Promise<Object>} 完整系统数据
       */
      all: async () => {
        const [users, papers, statistics] = await Promise.all([
          this.users.getAll(),
          this.papers.getAll(),
          this.getSystemStatistics()
        ]);

        return {
          metadata: {
            export_date: new Date().toISOString(),
            version: '1.0.0'
          },
          statistics,
          data: {
            users,
            papers
          }
        };
      }
    };
  }
}

// 创建单例实例
const databaseService = new DatabaseService();

module.exports = databaseService;
